package com.net.xpay.common.validator;

import com.net.xpay.common.domain.CheckCode;
import com.net.xpay.common.domain.CheckCodeLog;
import com.net.xpay.common.manager.CheckCodeLogManager;
import com.net.xpay.common.manager.CheckCodeManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.helper.EnvironmentHelper;
import com.net.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * Created by  on 2017/8/21.
 */
@Component
public class CheckCodeValidator {
    private static final String DEFAULT_TEST_CODE = "888888";

    private static final long MAX_ERROR_COUNT = 3L;

    @Autowired
    private CheckCodeManager checkCodeManager;

    @Autowired
    private CheckCodeLogManager checkCodeLogManager;

    @Autowired
    private EnvironmentHelper environmentHelper;

    public void validateCheckCode(CheckCode checkCode, String input) {
        {
            // 固定验证码
//            if (checkCode != null) {
//                checkCode.setCode("888888");
//            }
//            if (environmentHelper.isDevOrLocal() && DEFAULT_TEST_CODE.equals(input)) {
//                return;
//            }

            if (checkCode == null) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请先发送验证码");
            } else if (checkCode.getExpiredTime().isBefore(LocalDateTime.now())) {
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "验证码已过期，请重新发送");
            } else if (!Objects.equals(checkCode.getCode(), input)) {
                checkCode.setErrorCnt(checkCode.getErrorCnt() + 1L);
                checkCodeManager.update(checkCode);
                CheckCodeLog checkCodeLog = checkCodeLogManager.findLastByCheckCodeId(checkCode.getId());
                checkCodeLog.setErrorCnt(checkCode.getErrorCnt());
                checkCodeLogManager.update(checkCodeLog);

                if (checkCode.getErrorCnt() >= MAX_ERROR_COUNT) {
                    checkCodeManager.deleteById(checkCode.getId());
                    throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "验证码输错超过" + MAX_ERROR_COUNT
                            + "次，请重新发送验证码");
                }
                throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "验证码不正确");
            }
            //验证通过 删除掉验证码 使验证码失效
            checkCodeManager.deleteById(checkCode.getId());
            //记录验证通过信息
            CheckCodeLog checkCodeLog = checkCodeLogManager.findLastByCheckCodeId(checkCode.getId());
            checkCodeLog.setValid(true);
            checkCodeLogManager.update(checkCodeLog);
        }
    }

}
